import { createAsyncThunk, createSlice, type PayloadAction } from "@reduxjs/toolkit";
import type { addressItem } from "../../api/address";
import type { Commodity, ShopItem } from "../../api/shops";
import { addOrderAPI, type addOrderParams, type ResponseAddOrder } from "../../api/order";

type orderSubmitState = {
    error: null | string,
    loading: boolean,

    addressItem: addressItem | null,
    shopInfo: ShopItem | null,
    orderList: Commodity[] | null,
    tableware: boolean,
    remark: string

}
const initialState: orderSubmitState = {
    error: null,
    loading: false,

    addressItem: null,
    shopInfo: null,
    orderList: null,
    tableware: false,
    remark: ''

}

const orderSubmitSlice = createSlice({
    name: 'orderSubmit',
    initialState,
    reducers: {
        addOrderSubAddress(state, action: PayloadAction<addressItem>) {
            state.addressItem = action.payload
        },
        addOrderSubShopInfo(state, action: PayloadAction<ShopItem>) {
            state.shopInfo = action.payload
        },
        addOrderSubOrderList(state, action: PayloadAction<Commodity[]>) {
            state.orderList = action.payload
        },
        addOrderSubRemark(state, action: PayloadAction<string>) {
            state.remark = action.payload
        },
        addOrderSubTableware(state, action: PayloadAction<boolean>) {
            state.tableware = action.payload
        },
        //清除提交订单信息
        clearOrderSubmit(state) {
            state.addressItem = null
            state.orderList = null
            state.shopInfo = null
            state.tableware = false
            state.remark = ''
        }
    }, extraReducers: (builder) => {
        builder
            .addCase(submitOrder.pending, (state) => {
                state.error = null
                state.loading = true
            })
            .addCase(submitOrder.fulfilled, (state) => {
                state.loading = false
            })
            .addCase(submitOrder.rejected, (state, action) => {
                state.loading = false
                if (action.payload) {
                    state.error = action.payload
                }

            })
    }
})

export const { clearOrderSubmit, addOrderSubAddress, addOrderSubRemark, addOrderSubTableware, addOrderSubOrderList, addOrderSubShopInfo } = orderSubmitSlice.actions

export const orderSubmitReducer = orderSubmitSlice.reducer

export const submitOrder = createAsyncThunk<ResponseAddOrder, addOrderParams, { rejectValue: string }>("orderSubmit/submitOrder", async (data: addOrderParams, { rejectWithValue }) => {
    try {
        const res = await addOrderAPI(data)
        console.log(res)
        if (res.data.code === 0) {
            return res.data
        }else{
            return rejectWithValue(res.data.msg)
        }


    } catch (error) {
        return rejectWithValue(error + '')
    }
})